﻿using System;
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Web.Configuration;
using System.Web.UI.MobileControls;
using Controller.Helper;
using Core.Utilities;
using Microsoft.ServiceModel.Web;
using Model;
using Controller;
using Controller.Enum;
using Core;
using Microsoft.Reporting.WebForms;
using Controller.Class;
using System.IO;


namespace SalePriceSystem.Wcf
{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "serviceAPI.cs".
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceContract]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, MaxItemsInObjectGraph = 2147483646, IncludeExceptionDetailInFaults = true)]

    public class Service1
    {

        private List<JsonValue> items = new List<JsonValue>();

        [WebGet(UriTemplate = "{id}")]
        public JsonValue Get(string id)
        {
            dynamic query = WebOperationContext.Current.IncomingRequest.GetQueryStringAsJsonObject();

            // Look up item based on id and the value of the URI query string variable returnResult
            bool returnResult;
            if (query.returnResult.TryReadAs<bool>(out returnResult) && returnResult)
            {
                short index;
                if (Int16.TryParse(id, out index) && index < items.Count)
                {
                    return items[index];
                }
            }
            return null;
        }

        [WebGet(UriTemplate = "")]
        public JsonValue GetAll()
        {
            return new JsonArray(items);
        }

        [WebInvoke(UriTemplate = "", Method = "POST")]
        public JsonValue Post(JsonObject body)
        {
            dynamic item = body;
            item.id = items.Count;
            items.Add(item);
            return items[items.Count - 1];
        }

        [WebGet(UriTemplate = "/GetUserAD", ResponseFormat = WebMessageFormat.Json)]
        public JsonValue GetUserAd()
        {
            string name = ServiceSecurityContext.Current.PrimaryIdentity.Name;
            tblUser user = Controller.AD.LdapAuthentication.FindUser("w35939");
            return null;
        }

        [WebInvoke(UriTemplate = "/GetRoleDB", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public List<tblRole> GetRoleDB()
        {
            List<tblRole> roles = Controller.Helper.Member.GetRoleDb();

            return roles;
        }

        [WebInvoke(UriTemplate = "/GetUserDB", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public string GetUserDb()
        {
            //List<tblUser> users = Controller.Helper.Member.GetUserDB();
            string kk = Controller.Helper.Member.GetUserDBjson();
            return kk;
        }



        [WebInvoke(UriTemplate = "/UpdateRoleDB", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateRoleDb(JsonObject rolesData)
        {

            List<tblRole> roles = new List<tblRole>();
            JsonArray datas = rolesData.Values.ToJsonArray();
            foreach (dynamic role in datas)
            {
                tblRole r = new tblRole();
                r.RoleID = role.RoleID;
                r.RoleName = role.RoleName;
                r.RoleDescription = role.RoleDescription;
                string boolIsDisable = role.IsDisable;
                r.IsDisable = bool.Parse(boolIsDisable);
                roles.Add(r);
            }
            int result = Controller.Helper.Member.RoleAction(roles, EnumAction.Update);
            return result;

        }

        [WebInvoke(UriTemplate = "/UpdateProdHier", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateProdHier(JsonObject prodhiersData)
        {

            List<tblProductHier> productHiers = new List<tblProductHier>();
            JsonArray datas = prodhiersData.Values.ToJsonArray();
            foreach (dynamic prodhier in datas)
            {
                tblProductHier pl = new tblProductHier();
                pl.mprodhlName = prodhier.mprodhlName;
                pl.mprodh_length = prodhier.mprodh_length;
                pl.mprodhlSAP = prodhier.mprodhlSAP;
                string boolIsDisable = prodhier.isDisable;
                bool isdisable;
                bool.TryParse(boolIsDisable, out isdisable);
                pl.isDisable = isdisable;
                productHiers.Add(pl);
            }
            int result = Controller.Helper.ProductGrp.ProdHierAction(productHiers, EnumAction.Update);
            return result;

        }
        [WebInvoke(UriTemplate = "/UpdateUserDB", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateUserDB(JsonObject usersData)
        {

            List<tblUser> users = new List<tblUser>();
            JsonArray datas = usersData.Values.ToJsonArray();
            foreach (dynamic user in datas)
            {
                tblUser u = new tblUser();
                u.msalegrp = user.msalegrp;
                u.UserName = user.UserName;
                u.RoleName = user.RoleName;
                u.Tel = user.Tel;
                u.Fax = user.Fax;
                string boolIsDisable = user.IsDisable;
                bool isdisable;
                bool.TryParse(boolIsDisable, out isdisable);
                u.IsDisable = isdisable;
                users.Add(u);
            }
            int result = Controller.Helper.Member.UserAction(users, EnumAction.Update);
            return result;

        }

        [WebInvoke(UriTemplate = "/UpdateProdGrp", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateProdGrp(JsonObject prodGrpsData)
        {

            List<tblProductCate> pgs = new List<tblProductCate>();
            JsonArray datas = prodGrpsData.Values.ToJsonArray();
            foreach (dynamic prodgrp in datas)
            {
                tblProductCate pg = new tblProductCate();
                pg.mprodh_grpID = prodgrp.mprodh_grpID;
                pg.isDisable = prodgrp.isDisable;
                string boolIsDisable = prodgrp.IsDisable;
                bool isdisable;
                bool.TryParse(boolIsDisable, out isdisable);
                pg.isDisable = isdisable;
                pgs.Add(pg);
            }
            int result = 0;// Controller.Helper.ProductGrp.ProdGrpAction(pgs, EnumAction.Update);
            return result;

        }

        [WebInvoke(UriTemplate = "/InserDocument", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public string InserDocument(JsonObject documentData)
        {

            var docs = new List<tblDocument>();
            JsonArray datas = documentData.Values.ToJsonArray();
            int saveDocument = -1;
            System.Globalization.CultureInfo cultureinfo = System.Threading.Thread.CurrentThread.CurrentCulture;
            string[] pipeNeedConvert = { "53" };
            foreach (dynamic data in datas)
            {
                var d = new tblDocument();
                string sdocID = data.docID;
                if (string.IsNullOrEmpty(sdocID))
                {

                    string currentUser = Controller.AD.LdapAuthentication.GetCurrentUser();
                    string currentSaleGrp = Controller.AD.LdapAuthentication.GetCurrentSaleGrp();
                    string stringDocType = data.Doctype;
                    string docID = Controller.Helper.Document.createDocumentID(currentSaleGrp, stringDocType);
                    d.DocID = docID;
                    d.Doctype = data.Doctype;
                    d.Status = data.Status;
                    d.UserName = currentUser;
                    string creditTerm = data.CreditTerm;
                    try
                    {
                        int approvLevel = data.ApproveLevel;
                        d.ApproveLevel = approvLevel;
                    }
                    catch (Exception ex)
                    {

                        throw;
                    }

                    if (!string.IsNullOrEmpty(Controller.AD.LdapAuthentication.GetCurrentRepresendto()))
                    {
                        d.OwnerDoc = Controller.AD.LdapAuthentication.GetCurrentRepresendto();
                    }
                    else
                    {
                        d.OwnerDoc = Controller.AD.LdapAuthentication.GetCurrentUser();
                    }
                    d.Created = DateTime.Now;
                    d.Remark = data.Remark;
                    d.Remark2 = data.Remark2;
                    DateTime validOnDate = DateTime.Today;
                    DateTime validToDate = DateTime.Today;
                    string validOndataString = data.ValidOn;
                    string validTodataString = data.ValidTo;
                    if (!string.IsNullOrEmpty(validOndataString) || validOndataString != "null")
                    {
                        try
                        {
                            d.ValidON = DateTime.Parse(validOndataString, cultureinfo);
                        }
                        catch (Exception)
                        {
                            d.ValidON = null;
                        }

                    }
                    if (!string.IsNullOrEmpty(validTodataString) || validTodataString != "null")
                    {
                        try
                        {
                            d.ValidTO = DateTime.Parse(validTodataString, cultureinfo);
                        }
                        catch (Exception)
                        {
                            d.ValidTO = null;
                        }
                    }
                    d.IsDisable = false;
                    d.Common = "";
                    docs.Add(d);
                    int round = Controller.Helper.Document.DocumentAction(docs, EnumAction.Insert);
                    var dds = new List<tblDocumentDatail>();
                    var ddps = new List<tblDocumentDetailParent>();
                    foreach (var data2 in data.data)
                    {
                        
                        try
                        {
                            var dd = new tblDocumentDatail();
                            var ddp = new tblDocumentDetailParent();
                            dd.DocID = docID;
                            dd.DCID = data2.DCID;
                            dd.RefID = data2.RefID;
                            decimal ndprdice = data2.NDPrice;
                            
                            ndprdice = Convert.ToDecimal(ndprdice);
                            
                            string sProductDesc = data2.ProductDesc;
                            dd.ProductID = !string.IsNullOrEmpty(sProductDesc) ? Controller.Helper.ProductGrp.GetProductID(sProductDesc) : data2.ProductID;
                            
                            dd.discountPrice = data2.discountPrice;
                            dd.discountPrice = Math.Round(dd.discountPrice, 2);
                            if (!string.IsNullOrEmpty(creditTerm) && pipeNeedConvert.Any(i=> i == dd.ProductID))
                            {
                                dd.discountPriceBath = Controller.Helper.Document.GetBath(Math.Round((Convert.ToDecimal(dd.discountPrice - ndprdice) * -1),2), creditTerm);
                            }
                            dd.isDisable = false;
                            ddp.Docid = docID;
                            ddp.RefID = data2.RefID;
                            ddp.ParentText = data2.Parent;
                            //bool kkk = !ddps.Any(k => k.RefID.Trim() == ddp.RefID.Trim() && k.Docid == docID);
                            if (!ddps.Any(k => k.RefID.Trim() == ddp.RefID.Trim() && k.Docid == docID))
                            {
                                ddps.Add(ddp);
                            }
                            dds.Add(dd);
                        }
                        catch (Exception ex)
                        {
                        }

                    }
                    
                    saveDocument = Controller.Helper.Document.DocumentDetailAction(dds,ddps, EnumAction.Insert);
                }
                else
                {
                    string docID = data.docID;
                    d.DocID = docID;
                    d.Doctype = data.Doctype;
                    d.Status = data.Status;
                    d.UserName = Controller.AD.LdapAuthentication.GetCurrentUser();
                    string creditTerm = data.CreditTerm;
                    try
                    {
                        int approvLevel = data.ApproveLevel;
                        d.ApproveLevel = approvLevel;
                    }
                    catch (Exception ex)
                    {

                        throw;
                    }
                    if (!string.IsNullOrEmpty(Controller.AD.LdapAuthentication.GetCurrentRepresendto()))
                    {
                        d.OwnerDoc = Controller.AD.LdapAuthentication.GetCurrentRepresendto();
                    }
                    else
                    {
                        d.OwnerDoc = Controller.AD.LdapAuthentication.GetCurrentUser();
                    }
                    if (d.Status == "30" || d.Status == "11")
                    {
                        d.Created = DateTime.Now;
                    }
                    else
                    {
                        d.Created = DateTime.MinValue;
                    }
                    d.Remark = data.Remark;
                    d.Remark2 = data.Remark2;
                    DateTime validOnDate = DateTime.Today;
                    DateTime validToDate = DateTime.Today;
                    string validOndataString = data.ValidOn;
                    string validTodataString = data.ValidTo;

                    if (!string.IsNullOrEmpty(validOndataString) || validOndataString != "null")
                    {
                        try
                        {
                            d.ValidON = DateTime.Parse(validOndataString, cultureinfo);
                        }
                        catch (Exception)
                        {
                            d.ValidON = null;
                        }

                    }
                    if (!string.IsNullOrEmpty(validTodataString) || validTodataString != "null")
                    {
                        try
                        {
                            d.ValidTO = DateTime.Parse(validTodataString, cultureinfo);
                        }
                        catch (Exception)
                        {
                            d.ValidTO = null;
                        }
                    }
                    d.IsDisable = false;
                    d.Common = "";
                    docs.Add(d);
                    int round = Controller.Helper.Document.DocumentAction(docs, EnumAction.Update);
                    var dds = new List<tblDocumentDatail>();
                    var ddps = new List<tblDocumentDetailParent>();
                    foreach (var data2 in data.data)
                    {
                        try
                        {
                            var dd = new tblDocumentDatail();
                            var ddp = new tblDocumentDetailParent();
                            dd.DocID = docID;
                            dd.DCID = data2.DCID;
                            dd.RefID = data2.RefID;
                            decimal ndprdice = data2.NDPrice;
                            ndprdice = Convert.ToDecimal(ndprdice);
                            string sProductDesc = data2.ProductDesc;
                            dd.ProductID = Controller.Helper.ProductGrp.GetProductID(sProductDesc);
                            dd.discountPrice = data2.discountPrice;
                            dd.discountPrice = Math.Round(dd.discountPrice, 2);
                            dd.isDisable = false;
                            ddp.Docid = docID;
                            ddp.RefID = data2.RefID;
                            ddp.ParentText = data2.Parent;
                            if (!string.IsNullOrEmpty(creditTerm) && pipeNeedConvert.Any(i => i == dd.ProductID))
                            {
                                dd.discountPriceBath = Controller.Helper.Document.GetBath(Math.Round((Convert.ToDecimal(dd.discountPrice - ndprdice) * -1),2), creditTerm);
                            }
                            if (!ddps.Any(k => k.RefID.Trim() == ddp.RefID.Trim() && k.Docid == docID))
                            {
                                ddps.Add(ddp);
                            }
                            dds.Add(dd);
                        }
                        catch (Exception ex)
                        {
                        }

                    }
                    saveDocument = Controller.Helper.Document.DocumentDetailAction(dds,ddps, EnumAction.Update);

                }
                if (saveDocument > 0 && d.Status != "30")
                {
                    string sendresul = string.Empty;
                    string sale;
                    string maker;
                    if (!string.IsNullOrEmpty(Controller.AD.LdapAuthentication.GetCurrentRepresendto()))
                    {
                        maker = d.UserName;
                        sale = Controller.AD.LdapAuthentication.GetCurrentRepresendto();
                    }
                    else
                    {
                        maker = d.UserName;
                        sale = maker;
                    }
                    var emails = Controller.Helper.Approver.GetApprovalMailBySale(sale);//new List<string> { "redharing_555@hotmail.com" }; //Controller.Helper.Approver.GetApprovalMailBySale(sale); //
                    var emailSupject = WebConfigurationManager.AppSettings["ApproverEmailSupject"] ??
                                       "แจ้งเอกสารรอการอนุมติ";
                    var emailBody =
                        Core.GenericUtil.ReadFile(
                            System.Web.HttpContext.Current.Server.MapPath("/template/ApproverEmailTamplete.htm"));
                    var attached = RenderPDF(d.Doctype, d.DocID);
                    List<tblUser> usersMaker = Controller.Helper.Member.GetUserDB(maker); ;
                    List<tblUser> users = null;
                    users = sale != maker ? Controller.Helper.Member.GetUserDB(sale) : usersMaker;

                    var completeBody = string.Format(emailBody, d.DocID,
                                                     "คุณ " + usersMaker[0].FirstName + " " + usersMaker[0].Lastname,
                                                     users[0].msalegrp);
                    foreach (var email in emails)
                    {
                        string emailto = email;
                        EmailUtil.SendMail("salediscountprice@scg.co.th", emailto, emailSupject,
                                           completeBody, true, attached,out sendresul);
                    }
                    if (!string.IsNullOrEmpty(sendresul))
                    {
                        string pathsave = "/Log/";
                        string filename = pathsave + DateTime.Now.Day + "-" + DateTime.Now.Month + ".txt";
                        string complete = "SendEmail error =" + sendresul + DateTime.Now;
                        Core.GenericUtil.SaveFile(System.Web.HttpContext.Current.Server.MapPath(pathsave),
                                                  System.Web.HttpContext.Current.Server.MapPath(filename),
                                                  complete.ToString());
                        return complete;
                    }

                }
            }
            //int result = Controller.Helper.Member.UserAction(users, EnumAction.Update);
            return saveDocument.ToString();

        }

        [WebInvoke(UriTemplate = "/InserNDPrice", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int InserNdPrice(JsonObject ndPriceData)
        {

            List<tblNDPrice> ps = new List<tblNDPrice>();
            JsonArray datas = ndPriceData.Values.ToJsonArray();
            int saveNDPriceDetail = -1;
            System.Globalization.CultureInfo cultureinfo = System.Threading.Thread.CurrentThread.CurrentCulture;
            foreach (dynamic data in datas)
            {
                tblNDPrice p = new tblNDPrice();
                p.Createby = Controller.AD.LdapAuthentication.GetCurrentUser();
                p.Created = DateTime.Now;
                p.remark = data.remark;
                p.remark2 = data.remark2;
                DateTime validOnDate = DateTime.Today;
                DateTime validToDate = DateTime.Today;
                string validOndataString = data.ValidOn;
                string validTodataString = data.ValidTo;
                if (!string.IsNullOrEmpty(validOndataString) || validOndataString != "null")
                {
                    try
                    {
                        p.ValidON = DateTime.Parse(validOndataString, cultureinfo);
                    }
                    catch (Exception)
                    {
                        p.ValidON = null;
                    }

                }
                if (!string.IsNullOrEmpty(validTodataString) || validTodataString != "null")
                {
                    try
                    {
                        p.ValidTO = DateTime.Parse(validTodataString, cultureinfo);
                    }
                    catch (Exception)
                    {
                        p.ValidTO = null;
                    }
                }
                ps.Add(p);
                //int round = Controller.Helper.NDPrice.DocumentAction(ps, EnumAction.Insert);
                int round = Controller.Helper.NDPrice.GetLastestRound();
                List<tblNDPriceDetail> pds = new List<tblNDPriceDetail>();

                foreach (var data2 in data.data)
                {
                    tblNDPriceDetail pd = new tblNDPriceDetail();
                    pd.NDRound = round;
                    pd.mprodh_grpname = data2.mprodh_grpname;
                    if (data2.discountPrice == null)
                    {
                        pd.discountPrice = 0;
                    }
                    else
                    {
                        pd.discountPrice = data2.discountPrice;
                    }

                    pds.Add(pd);
                }
                saveNDPriceDetail = Controller.Helper.NDPrice.NdPriceDetailAction(pds, EnumAction.Update);
                //    u.UserName = user.UserName;
                //    u.RoleName = user.RoleName;
                //    string boolIsDisable = user.IsDisable;
                //    u.IsDisable = bool.Parse(boolIsDisable);
                //    users.Add(u);
            }
            //int result = Controller.Helper.Member.UserAction(users, EnumAction.Update);
            return saveNDPriceDetail;

        }

        [WebInvoke(UriTemplate = "/DeleteRole", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int DeleteRole(JsonObject roleName)
        {
            dynamic item = roleName;
            List<tblRole> roles = new List<tblRole>();
            JsonArray datas = item.roleName.ReadAs<JsonArray>();
            foreach (string _role in datas)
            {
                tblRole role = new tblRole();
                role.RoleName = _role.ToString();
                roles.Add(role);
            }
            try
            {
                int result = Controller.Helper.Member.RoleAction(roles, EnumAction.Delete);
                return result;

            }
            catch (Exception)
            {
                return -1;
            }
        }
        [WebInvoke(UriTemplate = "/DeleteProdHier", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int DeleteProdHier(JsonObject prodHierID)
        {
            dynamic item = prodHierID;
            List<tblProductHier> roles = new List<tblProductHier>();
            JsonArray datas = item.prodhier.ReadAs<JsonArray>();
            foreach (int prodHier in datas)
            {
                tblProductHier prohier = new tblProductHier();
                prohier.mprodh_levelno = prodHier;
                roles.Add(prohier);
            }
            try
            {
                int result = Controller.Helper.ProductGrp.ProdHierAction(roles, EnumAction.Delete);
                return result;

            }
            catch (Exception)
            {
                return -1;
            }
        }

        [WebInvoke(UriTemplate = "/DeleteUserAd", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int DeleteUserAd(JsonObject userName)
        {
            dynamic item = userName;
            List<tblUser> users = new List<tblUser>();
            JsonArray datas = item.userName.ReadAs<JsonArray>();
            foreach (string username in datas)
            {
                tblUser user = new tblUser();
                user.UserName = username.ToString();
                users.Add(user);
            }
            try
            {
                int result = Controller.Helper.Member.UserAction(users, EnumAction.Delete);
                return result;

            }
            catch (Exception)
            {
                return -1;
            }
            return 0;
        }

        [WebInvoke(UriTemplate = "/DeleteProdCate", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int DeleteProdCate(JsonObject prodCateID)
        {
            dynamic item = prodCateID;
            var productCates = new List<viewProductCate>();
            JsonArray datas = item.userName.ReadAs<JsonArray>();
            foreach (int prodcateid in datas)
            {
                var prodcate = new viewProductCate { mprodh_grpID = prodcateid };
                productCates.Add(prodcate);
            }
            try
            {
                int result = Controller.Helper.ProductGrp.ProdGrpAction(productCates, EnumAction.Delete);
                return result;

            }
            catch (Exception)
            {
                return -1;
            }
            return 0;
        }
        [WebInvoke(UriTemplate = "/AddRole", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int AddRole(JsonObject Role)
        {
            if (Role.Count > 0)
            {
                List<tblRole> roles = new List<tblRole>();
                JsonArray datas = Role.Values.ToJsonArray();
                foreach (dynamic _role in datas)
                {
                    tblRole r = new tblRole();
                    r.RoleName = _role.RoleName;
                    r.RoleDescription = _role.RoleDescription;
                    string booltest = _role.IsDisable;
                    r.IsDisable = bool.Parse(booltest);
                    r.CreateDate = DateTime.Now;
                    roles.Add(r);
                }
                int result = Controller.Helper.Member.RoleAction(roles, EnumAction.Insert);
                return result;
            }


            return -1;
        }

        [WebInvoke(UriTemplate = "/AddProdHier", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int AddProdHier(JsonObject ProdHier)
        {
            if (ProdHier.Count > 0)
            {
                List<tblProductHier> productHiers = new List<tblProductHier>();
                JsonArray datas = ProdHier.Values.ToJsonArray();
                foreach (dynamic _prodhier in datas)
                {
                    tblProductHier r = new tblProductHier();
                    r.mprodh_levelno = _prodhier.mprodh_levelno;
                    r.mprodhlName = _prodhier.mprodhlName;
                    r.mprodhlSAP = _prodhier.mprodhlSAP;
                    r.mprodh_length = _prodhier.mprodh_length;

                    productHiers.Add(r);
                }
                int result = Controller.Helper.ProductGrp.ProdHierAction(productHiers, EnumAction.Insert);
                return result;
            }


            return -1;
        }

        [WebInvoke(UriTemplate = "/AddUserAd", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int AddUserAd(JsonObject newUser)
        {
            if (newUser.Count > 0)
            {
                List<tblUser> users = new List<tblUser>();
                JsonArray datas = newUser.Values.ToJsonArray();
                foreach (dynamic _user in datas)
                {
                    string username = _user.UserName;
                    tblUser user = Controller.AD.LdapAuthentication.FindUser(username);
                    if (user == null)
                    {
                        user = new tblUser();
                        user.UserName = _user.UserName;
                        user.DomainName = "domainDefault";
                        user.Password = _user.Password;
                        user.FirstName = "Teerasak";
                        user.Lastname = "Chaihan";
                        user.Email = "redharing_555@hotmail.com";
                        user.RoleName = _user.RoleName;
                        user.msalegrp = _user.msalegrp;
                        user.CreateDate = DateTime.Now;
                        user.ModifyDate = DateTime.Now;
                        user.IsDisable = false;
                        user.Tel = _user.Tel;
                        user.Fax = _user.Fax;
                    }
                    else
                    {
                        user.Password = _user.Password;
                        user.RoleName = _user.RoleName;
                        user.msalegrp = _user.msalegrp;
                        user.CreateDate = DateTime.Now;
                        user.ModifyDate = DateTime.Now;
                        user.IsDisable = false;
                        user.Tel = _user.Tel;
                        user.Fax = _user.Fax;
                    }

                    users.Add(user);

                }
                int result = Controller.Helper.Member.UserAction(users, EnumAction.Insert);
                return result;

            }
            return -1;
        }

        [WebInvoke(UriTemplate = "/AddProductCate", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int AddProductCate(JsonObject newProdcate)
        {
            if (newProdcate.Count > 0)
            {
                var productCates = new List<viewProductCate>();
                JsonArray datas = newProdcate.Values.ToJsonArray();
                foreach (dynamic _prodcate in datas)
                {
                    string procatename = _prodcate.mprodh_grpname;
                    string procatecateLevelno = _prodcate.mprodh_levelno;
                    var prodcate = new viewProductCate { mprodh_grpname = procatename, mprodh_levelno = procatecateLevelno[0] };

                    //prodcate.isDisable = false;


                    productCates.Add(prodcate);

                }
                int result = Controller.Helper.ProductGrp.ProdGrpAction(productCates, EnumAction.Insert);
                return result;

            }
            return -1;
        }

        [WebInvoke(UriTemplate = "/UpdateApprovalMapping", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateApprovalMapping(JsonObject mappingList)
        {
            if (mappingList.Count > 0)
            {
                List<tblApprovalSaleMapping> mappings = new List<tblApprovalSaleMapping>();
                JsonArray datas = mappingList.Values.ToJsonArray();
                foreach (dynamic _mapping in datas)
                {
                    foreach (dynamic _m in _mapping)
                    {
                        tblApprovalSaleMapping maping = new tblApprovalSaleMapping();
                        maping.ApprovalUserName = _m.ApprovalUserName;
                        maping.SaleUsername = _m.SaleUsername;
                        mappings.Add(maping);
                    }
                    //tblUser user = Controller.AD.LdapAuthentication.FindUser(userName);

                }
                int result = Controller.Helper.Approver.ApproverAction(mappings, EnumAction.Insert);
                return result;

            }
            return -1;
        }

        [WebInvoke(UriTemplate = "/UpdateSaleMapping", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateSaleMapping(JsonObject mappingList)
        {
            if (mappingList.Count > 0)
            {
                List<tblSaleCoSaleMapping> mappings = new List<tblSaleCoSaleMapping>();
                JsonArray datas = mappingList.Values.ToJsonArray();
                foreach (dynamic _mapping in datas)
                {
                    foreach (dynamic _m in _mapping)
                    {
                        tblSaleCoSaleMapping maping = new tblSaleCoSaleMapping();
                        maping.SaleCoUserName = _m.SaleCoUserName;
                        maping.SaleUserName = _m.SaleUsername;
                        mappings.Add(maping);
                    }
                    //tblUser user = Controller.AD.LdapAuthentication.FindUser(userName);

                }
                int result = Controller.Helper.SaleCo.SaleCoAction(mappings, EnumAction.Insert);
                return result;

            }
            return -1;
        }

        [WebInvoke(UriTemplate = "/UpdateDocumentStatus", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateDocumentStatus(JsonObject DocumentList)
        {
            if (DocumentList.Count > 0)
            {
                List<tblDocument> documents = new List<tblDocument>();
                JsonArray datas = DocumentList.Values.ToJsonArray();
                System.Globalization.CultureInfo cultureinfo = System.Threading.Thread.CurrentThread.CurrentCulture;
                foreach (dynamic _d in datas)
                {
                    tblDocument document = new tblDocument();
                    //document.Doctype = _d.DocType;
                    document.DocID = _d.DocID;
                    document.Status = _d.Status;
                    document.Remark = _d.Remark;
                    document.Remark2 = _d.Remark2;
                    if (!string.IsNullOrEmpty(document.Status))
                    {
                        if (int.Parse(document.Status) == (int)EnumDocStatus.Approved)
                        {
                            document.ApproveDate = DateTime.Now;
                            document.ApproveBy = Controller.AD.LdapAuthentication.GetCurrentUser();
                        }
                        else if (int.Parse(document.Status) == (int)EnumDocStatus.Reject)
                        {
                            document.RejectDate = DateTime.Now;
                            document.ApproveBy = Controller.AD.LdapAuthentication.GetCurrentUser();
                        }
                        else if (int.Parse(document.Status) == (int)EnumDocStatus.ConfirmUploadToSap)
                        {
                            document.ComfirmUploadToSapDate = DateTime.Now;
                        }
                        else if (int.Parse(document.Status) == (int)EnumDocStatus.EditData)
                        {
                            document.EditDataDate = DateTime.Now;
                            document.Status = string.Empty;
                        }
                    }
                    DateTime validOnDate = DateTime.Today;
                    DateTime validToDate = DateTime.Today;
                    string validOndataString = _d.ValidOn;
                    string validTodataString = _d.ValidTo;
                    if (!string.IsNullOrEmpty(validOndataString) || validOndataString != "null")
                    {
                        try
                        {
                            document.ValidON = DateTime.Parse(validOndataString, cultureinfo);
                        }
                        catch (Exception)
                        {
                            document.ValidON = null;
                        }

                    }
                    if (!string.IsNullOrEmpty(validTodataString) || validTodataString != "null")
                    {
                        try
                        {
                            document.ValidTO = DateTime.Parse(validTodataString, cultureinfo);
                        }
                        catch (Exception)
                        {
                            document.ValidTO = null;
                        }
                    }
                    documents.Add(document);
                }
                //tblUser user = Controller.AD.LdapAuthentication.FindUser(userName);

                var roleAdmin = WebConfigurationManager.AppSettings["AdminRoleName"] ?? "Admin";
                int result = Controller.Helper.Document.DocumentAction(documents, EnumAction.Update);


                if (result != -1 && Controller.AD.LdapAuthentication.GetCurrentUserRole() == roleAdmin)
                {
                    foreach (var d in documents)
                    {
                        Controller.Helper.Document.UpdateIsUpdateByAdmin(d.DocID, true);
                    }
                }

                if (result != -1)
                {
                    foreach (var doc in documents)
                    {
                        if (doc.Status == "20")
                        {
                            var docCurrent = Controller.Helper.Document.GetDocumentByID(doc.DocID);
                            string owner = docCurrent.OwnerDoc;
                            string maker = docCurrent.UserName;
                            List<tblUser> usersOwner = Controller.Helper.Member.GetUserDB(owner);
                            List<tblUser> usersMaker = null;
                            if (owner != maker)
                            {
                                usersMaker = Controller.Helper.Member.GetUserDB(maker);
                            }
                            else
                            {
                                usersMaker = usersOwner;
                            }
                            var emailSupject = WebConfigurationManager.AppSettings["RejectEmailSupject"] ??
                                           "แจ้งเอกสารราคาส่วนลด Reject จากผู้อนุมัติ";
                            var emailBody =
                                Core.GenericUtil.ReadFile(
                                    System.Web.HttpContext.Current.Server.MapPath("/template/RejectEmailTemplete.htm"));
                            var completeBody = string.Format(emailBody, "คุณ " + usersMaker[0].FirstName + " " + usersMaker[0].Lastname,
                                                         doc.DocID,
                                                         "คุณ " + usersOwner[0].FirstName + " " + usersOwner[0].Lastname,
                                                         usersOwner[0].msalegrp);
                            //SalePriceSystem.Page.ReportViewer.
                            string sendresul = null;
                            EmailUtil.SendMail("salediscountprice@scg.co.th", usersMaker[0].Email, emailSupject,


                                           completeBody, true, out sendresul);







                            if (!string.IsNullOrEmpty(sendresul))
                            {
                                return -2;
                            }
                        }
                        else if (doc.Status == "10")
                        {
                            var docCurrent = Controller.Helper.Document.GetDocumentByID(doc.DocID);
                            string owner = docCurrent.OwnerDoc;
                            string maker = docCurrent.UserName;
                            List<tblUser> usersOwner = Controller.Helper.Member.GetUserDB(owner);
                            List<tblUser> usersMaker = null;
                            if (owner != maker)
                            {
                                usersMaker = Controller.Helper.Member.GetUserDB(maker);
                            }
                            else
                            {
                                usersMaker = usersOwner;
                            }
                            var emailSupject = WebConfigurationManager.AppSettings["ApprovedEmailSupject"] ??
                                           "แจ้งเอกสารราคาส่วนลด Approve จากผู้อนุมัติ";
                            var emailBody =
                                Core.GenericUtil.ReadFile(
                                    System.Web.HttpContext.Current.Server.MapPath("/template/ApprovedEmailTemplete.htm"));
                            var completeBody = string.Format(emailBody, "คุณ " + usersMaker[0].FirstName + " " + usersMaker[0].Lastname,
                                                         doc.DocID,
                                                         "คุณ " + usersOwner[0].FirstName + " " + usersOwner[0].Lastname,
                                                         usersOwner[0].msalegrp);
                            string sendresul = null;
                            EmailUtil.SendMail("salediscountprice@scg.co.th", usersMaker[0].Email, emailSupject,


                                           completeBody, true, out sendresul);







                            if (!string.IsNullOrEmpty(sendresul))
                            {
                                return -2;
                            }
                        }
                    }

                }

                return result;

            }
            return -1;
        }


        private string RenderPDF(string _doctype, string _docid)
        {
            var ds = Controller.Helper.Document.GetDocumentDetailByDocIDReport(_doctype, _docid);
            string username = "";
            string reportName = "";
            if (ds.Count > 0)
            {
                int approveLevel = 0;
                foreach (var d in ds)
                {
                    var value = d.ddiscountprice - d.discountPrice;
                    if (value <= d.level1)
                    {
                        if (approveLevel < 1)
                        {
                            approveLevel = 0;
                        }
                    }
                    else if (value > d.level1 && value <= d.level2)
                    {
                        if (approveLevel < 1)
                        {
                            approveLevel = 1;
                        }
                    }
                    else if (value > d.level2 && value <= d.level3)
                    {
                        if (approveLevel < 2)
                        {
                            approveLevel = 2;
                        }
                    }
                    else if (value > d.level3)
                    {
                        if (approveLevel < 3)
                        {
                            approveLevel = 3;
                        }
                    }
                    d.discountPrice = d.ddiscountprice - d.discountPrice;
                }
                username = ds[0].usernameOwner;
                reportName = username +"(" + _docid + ")";
                ds[0].approveLevel = approveLevel;
                ds[0].Status = "Wait for approve";
                List<tblUser> approvers = Controller.Helper.Member.GetUserDB(ds[0].approveByUserName);
                if (approvers.Count > 0)
                {
                    List<tblUser> us = Controller.Helper.Member.GetUserDB(approvers[0].UserName);
                    if (us.Count > 0)
                    {
                        ds[0].imageLicense = us[0].ImageLicense;
                    }
                }
                var approvalAll = Approver.GetAllApproveLevelObject();
                for (int i = 0; i < approvalAll.Count; i++)
                {
                    switch (i)
                    {
                        case 0:
                            ds[0].approverColor = approvalAll[0].warningColor;
                            ds[0].approverDisplay = approvalAll[0].approveDisplay;
                            break;
                        case 1:
                            ds[0].approver1Color = approvalAll[1].warningColor;
                            ds[0].approver1Display = approvalAll[1].approveDisplay;
                            break;
                        case 2:
                            ds[0].approver2Color = approvalAll[2].warningColor;
                            ds[0].approver2Display = approvalAll[2].approveDisplay;
                            break;
                        case 3:
                            ds[0].approver3Color = approvalAll[3].warningColor;
                            ds[0].approver3Display = approvalAll[3].approveDisplay;
                            break;
                        case 4:
                            ds[0].approver4Color = approvalAll[4].warningColor;
                            ds[0].approver4Display = approvalAll[4].approveDisplay;
                            break;

                    }
                }


                string outputPath = "C:\\Temp\\{0}.pdf";
                outputPath = string.Format(outputPath, reportName);
                var ReportViewer1 = new ReportViewer();
                ReportViewer1.LocalReport.EnableExternalImages = true;
                
                ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds));
                ReportViewer1.LocalReport.ReportPath = "Reports\\ReportDocDetailToPdf.rdlc";
                Warning[] warnings;
                string[] streamids;
                string mimeType;
                string encoding;
                string extension;
                string deviceInfo = "";
                byte[] bytes = ReportViewer1.LocalReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);
                using (FileStream fs = new FileStream(outputPath, FileMode.Create))
                {
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Close();
                }
                return outputPath;
            }
            return "";
        }
        [WebInvoke(UriTemplate = "/UpdateListDocumentStatus", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public int UpdateListDocumentStatus(JsonObject DocumentList)
        {

            if (DocumentList.Count > 0)
            {
                dynamic item = DocumentList;
                JsonArray datas = item.DocumentList.ReadAs<JsonArray>();
                List<tblDocument> documents = new List<tblDocument>();
                //JsonArray datas = DocumentList.

                foreach (dynamic _d in datas)
                {
                    tblDocument document = new tblDocument();
                    //document.Doctype = _d.DocType;
                    document.DocID = _d.DocID;
                    document.Status = _d.Status;
                    if (document.Status.ToString() != "50")
                    {
                        document.Remark = _d.Remark;
                        document.Remark2 = _d.Remark2;
                    }
                    else
                    {
                        document.Remark = "nochange";
                        document.Remark2 = "nochange";
                    }

                    if (!string.IsNullOrEmpty(document.Status))
                    {
                        if (int.Parse(document.Status) == (int)EnumDocStatus.Approved)
                        {
                            document.ApproveDate = DateTime.Now;
                        }
                        else if (int.Parse(document.Status) == (int)EnumDocStatus.Reject)
                        {
                            document.RejectDate = DateTime.Now;
                        }
                        else if (int.Parse(document.Status) == (int)EnumDocStatus.ConfirmUploadToSap)
                        {
                            document.ComfirmUploadToSapDate = DateTime.Now;
                        }
                        else if (int.Parse(document.Status) == (int)EnumDocStatus.EditData)
                        {
                            document.EditDataDate = DateTime.Now;
                        }
                    }
                    documents.Add(document);
                }
                //tblUser user = Controller.AD.LdapAuthentication.FindUser(userName);


                int saveDocument = Controller.Helper.Document.DocumentAction(documents, EnumAction.Update);
                if (saveDocument > 0)
                {
                    foreach (var tblDocument in documents)
                    {
                        //tblDocument d = Controller.Helper.Document.GetDocumentByID(tblDocument.DocID);
                        var docCurrent = Controller.Helper.Document.GetDocumentByID(tblDocument.DocID);
                        string owner = docCurrent.OwnerDoc;
                        string maker = docCurrent.UserName;
                        List<tblUser> usersOwner = Controller.Helper.Member.GetUserDB(owner);
                        List<tblUser> usersMaker = null;
                        if (owner != maker)
                        {
                            usersMaker = Controller.Helper.Member.GetUserDB(maker);
                        }
                        else
                        {
                            usersMaker = usersOwner;
                        }
                        //var emails = Controller.Helper.Approver.GetApprovalMailBySale(sale);
                        var emailSupject = WebConfigurationManager.AppSettings["CompleteEmailSupject"] ??
                                           "แจ้งเอกสารราคาส่วนลดอัพโหลดขึ้น SAP";
                        var emailBody =
                            Core.GenericUtil.ReadFile(
                                System.Web.HttpContext.Current.Server.MapPath("/template/CompleteEmailTemplete.htm"));
                        //List<tblUser> users = Controller.Helper.Member.GetUserDB(sale);
                        var completeBody = string.Format(emailBody, "คุณ " + usersOwner[0].FirstName + " " + usersOwner[0].Lastname,
                                                         docCurrent.DocID);
                        string sendresul = string.Empty;
                        foreach (var email in usersOwner)
                        {
                            string emailto = email.Email;
                            EmailUtil.SendMail("salediscountprice@scg.co.th", emailto, emailSupject,
                                               completeBody, true, out sendresul);
                        }


                        if (!string.IsNullOrEmpty(sendresul))
                        {
                            return -1;
                        }
                    }


                }
                return saveDocument;

            }
            return -1;
        }
    }
}

